package com.tim.source.templete;

import java.io.IOException;
import java.io.InputStream;

import com.tim.source.MakeSource;
import com.tim.source.common.CommonInfo;
import com.tim.source.common.TableInfo;
import com.tim.source.util.StringUtil;

/**
 * 数据表转hbm.xml.
 * 
 * @author Tim.
 * 
 */
public class TableToDaoImpl {
	// DaoImpl类名称
	public static String CLASS;
	// DaoImpl完整类路径.
	public static String FULL_CLASS;
	// DaoImpl类文件模板.
	private static String TEMPLETE;
	static {
		try {
			// 获取DaoImpl模板.
			InputStream input = TableToDaoImpl.class
					.getResourceAsStream("daoImpl.tmp");
			byte[] data = new byte[input.available()];
			input.read(data);
			TEMPLETE = new String(data, "UTF-8");
			// 替换文件创建时间.
			TEMPLETE = TEMPLETE.replace("%dateTime%", CommonInfo.DATESTRING);
			// 替换文件创建作者.
			TEMPLETE = TEMPLETE.replace("%author%", CommonInfo.AUTHOR);
			input.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static String execute() {
		// 替换package语句
		FULL_CLASS = MakeSource.DAO_IMPL.replace("/", ".");
		if (FULL_CLASS.endsWith(".")) {
			// 目前获取的为package
			FULL_CLASS = FULL_CLASS.substring(0, FULL_CLASS.lastIndexOf("."));
		}
		TEMPLETE = TEMPLETE.replace("%package%", FULL_CLASS);
		// 设置完整类名
		// 替换import语句
		StringBuilder importStr = new StringBuilder();
		// 导入Entity类
		importStr.append(StringUtil.getImportString(TableInfo.fullClassName));
		importStr.append("\r\n");
		// 导入Service接口
		importStr.append(StringUtil.getImportString(TableToIDao.FULL_CLASS));
		String tempStr = TEMPLETE.replace("%importList%", importStr.toString());
		// 替换类声明
		tempStr = tempStr.replace("%className%", TableInfo.className);
		// 设置类名
		CLASS = TableInfo.className + "DaoImpl";
		// 设置完整类名
		FULL_CLASS = FULL_CLASS + "." + CLASS;
		return tempStr;
	}
}
